package com.songVersion.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class HttpHelper
{
	public static String doGet(String sUrl, Map<String, String> params)
	{

		sUrl += getParams(params);
//		System.out.println(sUrl);

		try
		{
			URL url = new URL(sUrl);
			
			
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401");
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    connection.getInputStream()));
			
			
			String line;
			StringBuffer sb = new StringBuffer();
			while ((line = in.readLine()) != null)
			{
				sb.append(line);
			}
			
			
			return sb.toString();
			
			
		} catch (Exception e)
		{
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	private static String getParams(Map<String, String> params)
	{
		StringBuffer bf = new StringBuffer("");
		if (params != null && params.size() > 0)
		{
			bf.append("?");
			boolean first = true;
			for (String name : params.keySet())
			{
				if (first)
					first = false;
				else
					bf.append("&");

				try
				{
					bf.append(URLEncoder.encode(name, "UTF-8")).append("=")
							.append(
									URLEncoder
											.encode(params.get(name), "UTF-8"));
				} catch (UnsupportedEncodingException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return bf.toString();
	}

	public static void main(String[] args)
	{
		String resp = doGet("http://www.google.com", null);
		System.out.println(resp);
	}
	/*
	 * public static String doGet(String url, Map<String, String> params) {
	 * 
	 * HttpClient client = new DefaultHttpClient(); try { url +=
	 * getParams(params); System.out.println(url); HttpGet httpget = new
	 * HttpGet(url); ResponseHandler<String> responseHandler = new
	 * BasicResponseHandler(); String response = client.execute(httpget,
	 * responseHandler); return response; }catch (Exception e) {
	 * e.printStackTrace(); throw new RuntimeException(e); } finally {
	 * client.getConnectionManager().shutdown(); } }
	 */

}
